import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:ichinesereader/controller/assessments.dart';
import 'package:ichinesereader/controller/cache.dart';
import 'package:ichinesereader/controller/schooladmin.dart';
import 'package:ichinesereader/models/assessment/assessmentDto.dart';
import 'package:ichinesereader/models/book/BookItem.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:reactive_date_time_picker/reactive_date_time_picker.dart';
import 'package:reactive_dropdown_search/reactive_dropdown_search.dart';
import 'package:reactive_segmented_control/reactive_segmented_control.dart';
import 'package:get/get.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/models/forms/forms.dart';
import 'package:ichinesereader/models/assessment/assessmentItem.dart';

// ignore: must_be_immutable
class AssessmentSteps extends StatefulWidget {
  bool isNew;
  List<BookItem>? books;
  AssessmentItem? assessmentItem;
  String? assessmentId;
  String? type;
  String? from;
  AssessmentSteps({
    Key? key,
    required this.isNew,
    this.books,
    this.assessmentItem,
    this.assessmentId,
    this.type,
    this.from,
  }) : super(key: key);
  @override
  State<AssessmentSteps> createState() => _AssessmentStepsState();
}

class _AssessmentStepsState extends State<AssessmentSteps> {
  final formmodel = new HomeworkFormModel();
  List<BookItem> _bookItems = [];
  var box = Hive.box('appconfig');
  SchoolAdminController _controller = Get.find();
  AssessmentsController _assessmentsController = Get.find();
  List<String> _students = [];
  List<String> _userNames = [];
  String classId = '';
  late FormGroup form;
  String title = '';

  void _onSubmit() async {
    Log.debug(this.formmodel.form.value);
    if (!form.valid) {
      form.markAllAsTouched();
      return;
    }
    try {
      if (_bookItems.length > 0) {
        AssessmentDto dto = new AssessmentDto();
        if (this.formmodel.form.control('settings.allstudents').value != null &&
            this.formmodel.form.control('settings.allstudents').value == true) {
          dto.studentUserNames = _userNames;
        } else {
          //dto.allStudentInClass = false;
          if (this.formmodel.form.control('settings.students').value != null) {
            List<String> _selectedStudents =
                this.formmodel.form.control('settings.students').value;
            if (_selectedStudents.length > 0) {
              List<String> _namelist = [];
              _selectedStudents.forEach((element) {
                int start = element.indexOf(' - ');
                var tempstr = element.substring(0, start);
                _namelist.add(tempstr);
              });
              dto.studentUserNames = _namelist;
            } else {
              dto.studentUserNames = null;
            }
          }
        }

        List<String> _bookIds = [];
        _bookItems.forEach((element) {
          _bookIds.add(element.bookId.toString());
        });
        dto.classId = classId;
        dto.name = this.formmodel.form.control('settings.name').value;
        var startdate =
            this.formmodel.form.control('settings.startdate').value as DateTime;
        dto.startTime = startdate.millisecondsSinceEpoch;
        var enddate =
            this.formmodel.form.control('settings.duedate').value as DateTime;
        dto.endTime = enddate.millisecondsSinceEpoch;

        dto.instruction =
            this.formmodel.form.control('settings.instruction').value;

        dto.audioType = this.formmodel.form.control('features.audiotype').value;
        dto.textType = this.formmodel.form.control('features.texttype').value;
        if (widget.assessmentId != '' && widget.assessmentId != null) {
          dto.id = widget.assessmentId;
        }
        //定义的时候把question group id 和 type分别存在了content link和bookcode字段里
        //for edit--widget.type
        dto.questionGroupId = _bookItems[0].bookContentLink;
        dto.type = _bookItems[0].bookCode ?? widget.type;
        if (dto.type!.startsWith('IBDP_')) dto.kind = 'SPEAKING';
        _assessmentsController
            .createAssessment(dto, widget.assessmentId)
            .then((response) {
          if (response.status == 1000) {
            Get.snackbar(
                'Message'.tr, 'Assessment has been created successfully.'.tr,
                backgroundColor: Theme.of(context).primaryColor,
                colorText: Theme.of(context).primaryColorLight,
                snackPosition: SnackPosition.BOTTOM);
            // Get.offAndToNamed('/teacher/assessments');
            Get.toNamed('/teacher/assessments');
          } else {
            Get.snackbar('Message'.tr, 'Failed to create assessment.'.tr,
                backgroundColor: Theme.of(context).primaryColor,
                colorText: Theme.of(context).primaryColorLight,
                snackPosition: SnackPosition.BOTTOM);
          }
        });
      }
    } catch (error) {
      Get.snackbar('Message'.tr, 'Failed to create assessment.'.tr,
          backgroundColor: Theme.of(context).primaryColor,
          colorText: Theme.of(context).primaryColorLight,
          snackPosition: SnackPosition.BOTTOM);
      Log.debug(error);
    }
  }

  continued() {
    if (this.formmodel.form.valid)
      _onSubmit();
    else {
      Log.debug(this.formmodel.form.value);
      this.formmodel.form.markAllAsTouched();
    }
  }

  @override
  void initState() {
    classId = box.get(CacheManagerKey['currentclass'].toString());
    if (classId != '') _controller.fetchClassDetailsNewByClassId(classId);
    if (widget.books != null) _bookItems = widget.books as List<BookItem>;
    //_assessmentBookType = widget.assessmentBookType;
    if (widget.isNew == true && widget.books != null) {
      title = 'Create Assessment'.tr;
      form = this.formmodel.form;
      form.control('settings.allstudents').value = true;
    } else {
      title = 'Edit Assessment'.tr;
      form = this.formmodel.form;
      form.control('settings.allstudents').value = true;
      var assessment = widget.assessmentItem;
      // form.control('settings.allstudents').value =
      //     assessment?.allStudentInClass ?? false;
      form.control('settings.name').value = assessment?.name;
      if (widget.from == 'edit') {
        form.control('settings.startdate').value = assessment?.startDate;
        form.control('settings.duedate').value = assessment?.dueDate;
      }
      form.control('settings.instruction').value = assessment?.instructions;
      List<String> usernames = [];
      if (widget.assessmentItem?.students != null) {
        widget.assessmentItem?.students?.forEach((ministudent) {
          usernames.add(
              '${ministudent.userName} - ${ministudent.firstName} ${ministudent.lastName}');
        });
      }
      form.control('settings.students').value = usernames;
      form.control('features.texttype').value = assessment?.textType;
      form.control('features.audiotype').value = assessment?.audioType;
    }

    super.initState();
  }

  // ignore: unused_element
  void _handleRemoveChanged(String? bookId) {
    var newItems =
        _bookItems.where((element) => element.bookId != bookId).toList();
    setState(() {
      _bookItems = newItems;
    });
    form = formmodel.form;
    form.control('review.totalbooks').value = newItems.length;
    form.control('review.completerequired').value = newItems.length;
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('build AssessmentSteps');

    return Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: AppBar(
          leading: BackButton(
            onPressed: () {
              _assessmentsController
                  .refreshSelectedAssessmentBenchmarkTestbooks();
              Navigator.of(context).pop();
            },
          ),
          title: Text(title),
        ),
        body: SingleChildScrollView(child: Obx(() {
          if (_controller.classDetailsNew.value.studentResps != null &&
              _controller.classDetailsNew.value.studentResps!.isNotEmpty) {
            _students.clear();
            _userNames.clear();
            for (int i = 0;
                i < _controller.classDetailsNew.value.studentResps!.length;
                i++) {
              var usernamestring = _controller
                      .classDetailsNew.value.studentResps![i].userName
                      .toString() +
                  ' - ' +
                  _controller.classDetailsNew.value.studentResps![i].firstName
                      .toString() +
                  ' ' +
                  _controller.classDetailsNew.value.studentResps![i].lastName
                      .toString();
              _students.add(usernamestring);
              _userNames.add(_controller
                  .classDetailsNew.value.studentResps![i].userName
                  .toString());
            }
            return Padding(
              padding: const EdgeInsets.fromLTRB(36, 18, 36, 18),
              child: ReactiveForm(
                formGroup: form,
                child: Column(
                  children: <Widget>[
                    FormBuilderChoiceChip(
                      decoration: InputDecoration(
                          labelText: '', border: InputBorder.none),
                      name: 'subprogram_choice_chip',
                      onChanged: (value) {
                        //if (value == null) return;
                        //var item = value as BookItem;
                        // only 1 book curent
                        //_handleRemoveChanged(item.bookId);
                      },
                      options: _bookItems
                          .map((item) => FormBuilderChipOption<BookItem>(
                                value: item,
                                child: RichText(
                                  text: TextSpan(
                                    children: [
                                      TextSpan(
                                        text: '${item.bookTitle.toString()}',
                                        style: TextStyle(
                                          color: Colors.black,
                                          fontSize: 15,
                                          letterSpacing: 0,
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ))
                          .toList(),
                    ),
                    SizedBox(
                      height: 18,
                    ),
                    ReactiveTextField(
                      formControlName: 'settings.name',
                      textInputAction: TextInputAction.next,
                      style: Theme.of(context).textTheme.titleSmall,
                      onSubmitted: (_) => form.focus('settings.students'),
                      decoration: InputDecoration(
                        labelText: '*Task Name'.tr,
                      ),
                      validationMessages: {
                        ValidationMessage.required: (_) =>
                            'The task name must not be empty'.tr
                      },
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveCheckboxListTile(
                      formControlName: 'settings.allstudents',
                      title: Text(
                        'All Students?'.tr,
                        style: Theme.of(context).textTheme.titleSmall,
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveValueListenableBuilder<bool>(
                      formControlName: 'settings.allstudents',
                      builder: (context, control, child) {
                        return Visibility(
                            visible: !(control.value ?? false),
                            child: Column(
                              children: [
                                ReactiveDropdownSearchMultiSelection<String,
                                    String>(
                                  formControlName: 'settings.students',
                                  dropdownDecoratorProps:
                                      DropDownDecoratorProps(
                                    dropdownSearchDecoration: InputDecoration(
                                      hintText: "Select students".tr,
                                      labelText: "Students".tr,
                                    ),
                                  ),
                                  popupProps: PopupPropsMultiSelection.menu(
                                      showSelectedItems: true,
                                      showSearchBox: true),
                                  items: _students,
                                  showClearButton: true,
                                ),
                                SizedBox(
                                  height: 12,
                                ),
                              ],
                            ));
                      },
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveDateTimePicker(
                      formControlName: 'settings.startdate',
                      firstDate: DateTime.now(),
                      lastDate: DateTime.now().add(Duration(days: 365)),
                      type: ReactiveDatePickerFieldType.dateTime,
                      style: Theme.of(context).textTheme.titleSmall,
                      decoration: InputDecoration(
                        labelText: 'Start Date'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                        suffixIcon: Icon(Icons.calendar_today),
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveDateTimePicker(
                      formControlName: 'settings.duedate',
                      firstDate: DateTime.now(),
                      lastDate: DateTime.now().add(Duration(days: 365)),
                      style: Theme.of(context).textTheme.titleSmall,
                      type: ReactiveDatePickerFieldType.dateTime,
                      decoration: InputDecoration(
                        labelText: 'Due Date'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                        suffixIcon: Icon(Icons.calendar_today),
                      ),
                    ),
                    SizedBox(
                      height: 18,
                    ),
                    ReactiveTextField(
                      formControlName: 'settings.instruction',
                      maxLines: 3,
                      textInputAction: TextInputAction.next,
                      style: Theme.of(context).textTheme.titleSmall,
                      decoration: InputDecoration(
                        alignLabelWithHint: true,
                        labelText: 'Instructions'.tr,
                      ),
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveSegmentedControl<String, String>(
                      formControlName: 'features.audiotype',
                      decoration: InputDecoration(
                        labelText: 'Audio'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                      ),
                      padding: const EdgeInsets.all(0),
                      unselectedColor: Get.theme.primaryColorLight,
                      children: {
                        'Mandarin': Text('Mandarin'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                        'Cantonese': Text('Cantonese'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                      },
                    ),
                    SizedBox(
                      height: 12,
                    ),
                    ReactiveSegmentedControl<String, String>(
                      formControlName: 'features.texttype',
                      decoration: InputDecoration(
                        labelText: 'Text'.tr,
                        border: OutlineInputBorder(),
                        helperText: '',
                      ),
                      padding: const EdgeInsets.all(0),
                      unselectedColor: Get.theme.primaryColorLight,
                      children: {
                        'Simplified': Text('Simplified'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                        'Traditional': Text('Traditional'.tr,
                            style: TextStyle(
                              color: Color(0xff00599b),
                              fontSize: 16.0,
                              letterSpacing: 1.0,
                            )),
                      },
                    ),
                    SizedBox(
                      height: 18,
                    ),
                    Row(
                      children: <Widget>[
                        ElevatedButton(
                          onPressed: continued,
                          child: Text('Submit'.tr),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            );
          } else {
            return Text('');
          }
        })));
  }
}
